package com.gardenguell.salad.ui.activity.base;

import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;
import com.gardenguell.salad.R;

/**
 * Created by absurd on 2015/11/29.
 */
public abstract class ToolbarActivity extends BaseActivity{

    abstract protected int provideContentViewId();


    public void onToolbarClick() {}


    protected AppBarLayout mAppBar;
    protected Toolbar mToolbar;
    protected TextView mToolbarTitle;
    protected boolean mIsHidden = false;


    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(provideContentViewId());

        mAppBar = (AppBarLayout) findViewById(R.id.app_bar_layout);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbarTitle = (TextView)findViewById(R.id.toolbar_title);
        mToolbar.setTitle("");

        if (mToolbar == null || mAppBar == null) {
            throw new IllegalStateException("No toolbar");
        }

        mToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onToolbarClick();
            }
        });

        setSupportActionBar(mToolbar);

        if (canBack()) {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null)
                actionBar.setDisplayHomeAsUpEnabled(true);
        }

        if (Build.VERSION.SDK_INT >= 21) {
            mAppBar.setElevation(0f);
        }
    }

    public void hideToolbar(){
        mToolbar.setVisibility(View.GONE);
    }

    public void showToolbar(){
        mToolbar.setVisibility(View.VISIBLE);
    }

    public void setToolbarTitle(String title){
        mToolbarTitle.setText(title);
    }

    public void setToolbarColor(int color){
        mToolbar.setBackgroundColor(color);
    }


    public boolean canBack() {
        return false;
    }


    @Override public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        else {
            return super.onOptionsItemSelected(item);
        }
    }


    protected void setAppBarAlpha(float alpha) {
        mAppBar.setAlpha(alpha);
    }


    protected void hideOrShowToolbar() {
        mAppBar.animate()
                .translationY(mIsHidden ? 0 : -mAppBar.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();

        mIsHidden = !mIsHidden;
    }


}
